package cn.hxzy.teacher.service.impl;


import cn.hxzy.common.domain.ClassMenu;
import cn.hxzy.common.domain.ClassTable;
import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.vo.ClassStudentVo;
import cn.hxzy.common.domain.vo.SelectClass;
import cn.hxzy.common.domain.vo.TeacherClassVo;
import cn.hxzy.teacher.mapper.*;
import cn.hxzy.common.response.R;
import cn.hxzy.teacher.service.TeacherService;
import cn.hxzy.common.util.ThreadLocalUtil;
import cn.hxzy.user.mapper.ClassMenuMapper;
import cn.hxzy.user.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author LiDong
 * @Description
 * @create 2024/6/22 15:09
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private ClassMapper classTableMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassMenuMapper classMenuMapper;

    @Autowired
    private SelectClassMapper selectClassMapper;

    @Autowired
    private TaskManagerMapper01 taskManagerMapper01;

    @Override
    public boolean createClassroom(ClassTable classTable) {
        int insert = classTableMapper.insert(classTable);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据班级名称查询班级
     *
     * @param className
     * @return
     */
    @Override
    public int selectOneClass(String className) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("class_name", className);
        ClassTable classTable = classTableMapper.selectOne(queryWrapper);
        if (classTable != null) {
            return 1;
        }
        return 0;
    }

    /**
     * 根据教师Id查询班级
     *
     * @param teacherId
     * @return
     */
    @Override
    public List<SelectClass> findClassroomByTeacherId(Integer teacherId) {
        List<ClassTable> classList = classTableMapper.selectList(new QueryWrapper<ClassTable>()
                .eq("create_id", teacherId));
        List<SelectClass> list = new ArrayList<>();
        classList.forEach(arr -> {
            SelectClass selectClass = new SelectClass();
            String createName = selectClassMapper.getCreateNameById(teacherId);
            Integer studentNum = userMapper.selectUserCount(arr.getClassId());
            Integer courseNum = selectClassMapper.getCourseNum(arr.getClassId());
            selectClass.setCreateName(createName);
            selectClass.setClassName(arr.getClassName());
            selectClass.setId(arr.getClassId());
            selectClass.setStudentNum(studentNum);
            selectClass.setCourseNum(courseNum);
            list.add(selectClass);
        });
        return list;
    }

    /**
     * 根据班级Id修改班级名称
     *
     * @param classId
     * @param className
     * @return
     */
    @Override
    public String updateClass(Integer classId, String className) {
        int i = classTableMapper.updateClass(classId, className);
        if (i > 0) {
            return "修改成功";
        }
        return "修改失败";
    }

    //删除班级
    @Override
    @Transactional
    public Boolean deleteClassroom(Long classroomId) {
        //删除班级之前先删除班级中间表
        classTableMapper.deleteClassTeacher(classroomId);
        classTableMapper.deleteClass(classroomId);
        return true;

    }


    /**
     * 模糊查询班级
     *
     * @param name
     * @return
     */
    @Override
    public List<SelectClass> findClassroomByName(String name, Integer teacherId) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        name = "%" + name + "%";
        List<ClassTable> classList = classTableMapper.selectClass(name, teacherId);
        List<SelectClass> list = new ArrayList<>();
        classList.forEach(arr -> {
            SelectClass selectClass = new SelectClass();
            String createName = selectClassMapper.getCreateNameById(teacherId);
            Integer studentNum = userMapper.selectUserCount(arr.getClassId());
            Integer courseNum = selectClassMapper.getCourseNum(arr.getClassId());
            selectClass.setCreateName(createName);
            selectClass.setClassName(arr.getClassName());
            selectClass.setId(arr.getClassId());
            selectClass.setStudentNum(studentNum);
            selectClass.setCourseNum(courseNum);
            list.add(selectClass);
        });
        return list;
    }


    @Override
    public List<ClassTable> findAllClassroom() {
        return classTableMapper.findAll();
    }

    @Override
    public List<ClassStudentVo> selectAllClassList(Integer courseId) {
        //创建前端返回数据模型
        ArrayList<ClassStudentVo> classStudentVos = new ArrayList<>();

        User user = ThreadLocalUtil.getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户信息为空");
        }
        //班级集合
        List<ClassTable> classTables = taskManagerMapper01.selectClassByTeacherId(user.getUserId());

        for (ClassTable classTable : classTables) {
            ClassStudentVo classStudentVo = new ClassStudentVo();

            //查询学生数量
            Integer studentNum = taskManagerMapper01.selectStudentNumByClassId(classTable.getClassId());
            //查询是否授权
            Integer isAuthorized = taskManagerMapper01.selectIsAuthorized(classTable.getClassId(), courseId);
            if (isAuthorized == 0) {
                classStudentVo = new ClassStudentVo(
                        classTable.getClassId(),
                        classTable.getClassName(),
                        studentNum,
                        false);
            } else {
                classStudentVo = new ClassStudentVo(
                        classTable.getClassId(),
                        classTable.getClassName(),
                        studentNum,
                        true);
            }
            classStudentVos.add(classStudentVo);
        }
        return classStudentVos;
    }


    @Override
    public List<TeacherClassVo> newfindClassroomByTeacherId(Integer teacherId) {
        //往前端响应的数据集合
        List<TeacherClassVo> teacherClasssVo = new ArrayList<>();
        //首先根据老的id查询该老师下的班级id
        List<Integer> classIds = classTableMapper.selectClassIdByTeacherId(teacherId);
        //遍历班级id集合 查找具体的班级相关信息
        for (Integer oneClassId : classIds) {
            TeacherClassVo t1 = new TeacherClassVo();
            //查询回来一个班级的信息
            ClassTable classTable = classTableMapper.selectClassByClassId(oneClassId);
            if (classTable == null) {
                // 如果班级不存在，跳过当前循环
                continue;
            }
            t1.setClassId(classTable.getClassId());//存入班级的id
            t1.setClassName(classTable.getClassName());
            t1.setMarjorId(classTable.getMarjorId());

            Integer studentNum = userMapper.selectUserCount(oneClassId);
            Integer courseNum = selectClassMapper.getCourseNum(oneClassId);

            t1.setStudentNum(studentNum);
            t1.setCourseNum(courseNum);
            teacherClasssVo.add(t1);
        }
        return teacherClasssVo;
    }


    @Override
    public List<ClassStudentVo> selectClassBySearchKey(Integer courseId, String className, String createName, Integer isAuthorized) {
        List<ClassStudentVo> classStudentVos = selectAllClassList(courseId);

        if (StringUtils.isEmpty(className) && StringUtils.isEmpty(createName) && (isAuthorized == -1)) {
            // 如果所有参数都为空或 null，则返回原始列表
            return classStudentVos;
        }

        // 根据不同的条件组合进行过滤
        return classStudentVos.stream()
                .filter(classStudentVo -> {
                    boolean matchesClassName = StringUtils.isEmpty(className) || classStudentVo.getClassName().contains(className);
                    boolean matchesCreateName = StringUtils.isEmpty(createName) || classStudentVo.getCreatorName().contains(createName);
                    boolean matchesIsAuthorized = (isAuthorized == -1) || (isAuthorized == 1 && classStudentVo.getIsAuthorized()) || (isAuthorized == 0 && !classStudentVo.getIsAuthorized());

                    // 只要有一个条件满足即可通过过滤
                    return matchesClassName && matchesCreateName && matchesIsAuthorized;
                })
                .collect(Collectors.toList());
    }

    @Override
    public R createClassroomCourseAuthorized(String courseId, String classId, Boolean isAuthorized) {
        if (isAuthorized) {
            QueryWrapper<ClassMenu> classMenuQueryWrapper = new QueryWrapper<>();
            classMenuQueryWrapper.eq("class_id", classId);
            classMenuQueryWrapper.eq("course_id", courseId);
            List<ClassMenu> classMenus = classMenuMapper.selectList(classMenuQueryWrapper);
            if (classMenus.size() == 0) {
                ClassMenu classMenu = new ClassMenu();
                classMenu.setClassId(Integer.valueOf(classId));
                classMenu.setCourseId(Integer.valueOf(courseId));
                classMenuMapper.insert(classMenu);
            }
        } else {
            classMenuMapper.delete(new QueryWrapper<ClassMenu>().eq("class_id", classId).eq("course_id", courseId));
        }
        return R.success("操作成功");
    }


}


//    @Override
//    public List<ClassStudentVo> selectAllClassList(Integer courseId) {
//        User user = ThreadLocalUtil.getUser();
//        if (ObjectUtils.isEmpty(user)) {
//            throw new RuntimeException("用户信息为空");
//        }
//        QueryWrapper<ClassTable> classTableQueryWrapper = new QueryWrapper<>();
//        List<ClassTable> classTables=null;
//        if(!ObjectUtils.isEmpty(user.getSchoolId())){
//            classTableQueryWrapper.eq("school_id",user.getSchoolId());
//             classTables = classTableMapper.selectList(classTableQueryWrapper);
//        }
//        if(classTables.size() == 0){
//            throw new RuntimeException("该学校没有班级");
//        }
//        List<ClassTable> classTables = taskManagerMapper01.selectClassByTeacherId(user.getUserId());

//        List<ClassStudentVo> classStudentVos = classTables.stream().map(classTable -> {
//            ClassStudentVo classStudentVo = new ClassStudentVo();
//            BeanUtils.copyProperties(classTable, classStudentVo);
//            if (!StringUtils.isEmpty(classTable.getCreateId())) {
//                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//                userQueryWrapper.eq("user_id", classTable.getCreateId());
//                userQueryWrapper.eq("user_type", "2");
//                User userName = userMapper.selectById(classTable.getCreateId());
//                classStudentVo.setCreatorName(userName.getNickName());
//                classStudentVo.setCreateId(userName.getUserId());
//            }
//            if (!StringUtils.isEmpty(classTable.getClassId())) {
//                Integer userCount = userMapper.selectUserCount(classTable.getClassId());
//                classStudentVo.setStudentNumber(userCount);
//            }
//            //判断课程是否授权
//            QueryWrapper<ClassMenu> classMenuQueryWrapper = new QueryWrapper<>();
//            classMenuQueryWrapper.eq("class_id", classTable.getClassId());
//            classMenuQueryWrapper.eq("course_id", courseId);
//            Integer i = classMenuMapper.selectCount(classMenuQueryWrapper);
//            if (i > 0) {
//                classStudentVo.setIsAuthorized(true);
//            } else {
//                classStudentVo.setIsAuthorized(false);
//            }
//            return classStudentVo;
//        }).filter(classStudentVo -> user.getUserId() == classStudentVo.getCreateId()).collect(Collectors.toList());
//        return classStudentVos;
//    }